// pages/game/game.js
var Board = require('./grid.js')
var Main=require('./main.js')
const AV = require('../../utils/av-weapp-min.js')
Page({

  /**
   * 页面的初始数据
   */
  data: {
      start:"开始游戏",
      hidden:false,
      num:[],
      score:0,//此局最高分
      bestScore:0,//历史最高分
      bestCount:0,//历史最高连击
      maxCount: 0,//此局最高连击
      endMsg:"",
      over:false,
      newRecord:false
  },
  saveRecord:function(){
    var local_count=getApp().globalData.userInfo.count;
    var local_score = getApp().globalData.userInfo.score;
    const users=AV.User.current();
    if(local_count<this.data.maxCount){
      users.set('count',this.data.maxCount);
      users.save();
    }
    if (local_score < this.data.score) {
      users.set('score', this.data.score);
      users.save();
    }
    getApp().globalData.userInfo=users.attributes;
    var Record=AV.Object.extend('Record');
    var record=new Record();
    record.set("username", getApp().globalData.userInfo.username);
    record.set("count",this.data.maxCount);
    record.set("score",this.data.score);
    record.save().then(function(todo){
      console.log("success record");
    }, function(error){
      console.log(er)
    });
  },
  gameStart:function(){
    var main=new Main(4);
    this.setData({
      main:main
    })
    this.data.main.__proto__ = main.__proto__;
    this.setData({
      over:false,
      score:0,
      bestCount: wx.getStorageSync("bestCount"),
      bestScore: wx.getStorageSync("bestScore"),
      num:this.data.main.board.grid,
      newRecord:false
    })
  },
  touchStartX:0,
  touchStartY: 0,
  touchEndX:0,
  touchEndY: 0,
  touchStart:function(ev){ //触摸开始坐标
    var touch=ev.touches[0];
    this.touchStartX = touch.clientX;
    this.touchStartY=touch.clientY;

  },
  touchMove:function(ev){ //触摸最后移动时的坐标
    var touch = ev.touches[0];
    this.touchEndX = touch.clientX;
    this.touchEndY = touch.clientY;
  },
  touchEnd:function(){ //触摸离开的时候的坐标
    if(this.data.over){
      return;
    }
    var disX = this.touchStartX - this.touchEndX;
    var absdisX = Math.abs(disX);
    var disY = this.touchStartY - this.touchEndY;
    var absdisY = Math.abs(disY);
    if(this.data.main.isOver()){
      this.gameOver()
    }else{
      if (Math.max(absdisX, absdisY) > 10) { //确定是否在滑动
        this.setData({
          start: '重新开始'
        })
        var direction = absdisX > absdisY ? (disX < 0 ? 1 : 3) : (disY < 0 ? 2 : 0);//0：向上滑动 1：向右 2：向下 3：向左
        //console.log("方向："+direction);
        var dataList = this.data.main.move(direction);
        this.updateView(dataList);
      }
    }
    
  },
  gameOver(){
    this.setData({
      over:true
    })
    if(this.data.newRecord && this.data.maxCount>=2048){
      this.setData({
        endMsg:"恭喜达到2048，创造新纪录！"
      })
    } else if (this.data.maxCount >= 2048){
      this.setData({
        endMsg: "恭喜达到2048!"
      })
    } else if (this.data.newRecord){
      this.setData({
        endMsg: "创造新纪录！"
      })
    }else{
      this.setData({
        endMsg: "游戏结束！"
      })
    }
    this.saveRecord();
  },
  updateView(dataList){
    var max=0;
    for(var i=0;i<4;i++){
      for (var j = 0; j < 4; j++) {
        if (dataList[i][j] != "" && dataList[i][j]>max){
          max = dataList[i][j];
        }
      }
    }
    if(max>this.data.bestCount){
      wx.setStorageSync("bestCount", max);
      this.setData({
        bestCount:max,
        newRecord:true
      })
    }
    if(this.data.main.getScore()>this.data.bestScore){
      wx.setStorageSync("bestScore", this.data.main.getScore())
      this.setData({
        bestScore: this.data.main.getScore(),
        newRecord:true
      })
    }
    this.setData({
      num: dataList,
      score: this.data.main.getScore(),
      maxCount:max
    })
  },
  record_click:function(){
    wx.navigateTo({
      url: '../record/record',
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
  
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
      if(!wx.getStorageSync("bestCount")){
        wx.setStorageSync("bestCount", 2)
      }
      if (!wx.getStorageSync("bestScore")) {
        wx.setStorageSync("bestScore", 0)
      }
    this.gameStart();
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
  
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
  
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
  
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
  
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
  
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
  
  }
})